package com.cisystem.web.controller.business;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.cisystem.common.core.domain.entity.SysDept;
import com.cisystem.common.core.domain.model.LoginUser;
import com.cisystem.common.utils.SecurityUtils;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.framework.web.service.PermissionService;
import com.cisystem.system.domain.FileStore;
import com.cisystem.system.service.IFileStoreService;
import com.cisystem.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cisystem.common.annotation.Log;
import com.cisystem.common.core.controller.BaseController;
import com.cisystem.common.core.domain.AjaxResult;
import com.cisystem.common.enums.BusinessType;
import com.cisystem.system.domain.FileViewRecord;
import com.cisystem.system.service.IFileViewRecordService;
import com.cisystem.common.utils.poi.ExcelUtil;
import com.cisystem.common.core.page.TableDataInfo;

/**
 * 文件浏览记录Controller
 *
 * @author xxx
 * @date 2024-08-06
 */
@RestController
@RequestMapping("/business/record")
public class FileViewRecordController extends BaseController {
    @Autowired
    private IFileViewRecordService fileViewRecordService;

    @Autowired
    ISysDeptService deptService;

    @Autowired
    IFileStoreService fileStoreService;
    @Autowired
    PermissionService permissionService;
    /**
     * 查询文件浏览记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FileViewRecord fileViewRecord) {
        startPage();
        Date assignTime = fileViewRecord.getAssignTime();
        if (assignTime != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(assignTime);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date beginAssignTime = calendar.getTime();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date endAssignTime = calendar.getTime();
            Map<String, Object> params = fileViewRecord.getParams();
            fileViewRecord.setParams(params);
            params.put("beginAssignTime", beginAssignTime);
            params.put("endAssignTime", endAssignTime);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> permissions = loginUser.getPermissions();
        List<FileViewRecord> list = fileViewRecordService.selectFileViewRecordList(fileViewRecord);
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        if (!CollectionUtils.isEmpty(list)){
            List<String> fileids = new ArrayList<>();
            for (FileViewRecord viewRecord : list) {
                fileids.add(viewRecord.getFileId());
            }
            List<FileStore> fileStores = fileStoreService.listAllByFileIds(fileids);
            // 判断是或否过期
            Date date = new Date();
            Iterator<FileViewRecord> iterator = list.iterator();
            while (iterator.hasNext()){
                FileViewRecord record = iterator.next();
                if (!CollectionUtils.isEmpty(fileStores)){
                    for (FileStore fileStore : fileStores) {
                        if (fileStore.getId().equals(record.getFileId()) && "n".equals(fileStore.getVisible()) ){
                            String fileType = fileStore.getFileType();
                            if("first".equals(fileType) && !permissionService.hasPermissions(permissions,"business:first:visible")){
                                iterator.remove();
                            }else if ("dcc".equals(fileType) && !permissionService.hasPermissions(permissions,"business:dcc:visible")){
                                iterator.remove();
                            }else if (StringUtils.isEmpty(fileType) && !permissionService.hasPermissions(permissions,"business:file:visible") &&
                                !permissionService.hasPermissions(permissions,"business:dcc:visible")){
                                iterator.remove();
                            }
                            break;
                        }
                    }
                }
            }
            for (FileViewRecord record : list) {
                Date dueDate = record.getDueDate();
                String viewStatus = record.getViewStatus();
                if ("pending".equals(viewStatus) && dueDate != null && dueDate.before(date)) {
                    record.setViewStatus("overdue");
                    long l = date.getTime() - dueDate.getTime();
                    record.setOverdueDays((int) (l / (1000 * 60 * 60 * 24)));
                }else{
                    record.setOverdueDays(0);
                }
                for (SysDept sysDept : sysDepts) {
                    if (sysDept.getDeptId().equals(record.getAssignDeptId())) {
                        record.setDeptName(sysDept.getDeptName());
                        break;
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 修改文件浏览记录
     */
    @PostMapping("/view")
    public AjaxResult view(@RequestBody FileViewRecord fileViewRecord) {
        FileViewRecord fileViewRecord2 = fileViewRecordService.selectFileViewRecordById(fileViewRecord.getId());
        if (fileViewRecord2 != null){
            fileViewRecord2.setViewCount(fileViewRecord2.getViewCount()+1);
            fileViewRecord2.setUpdateTime(new Date());
            return toAjax(fileViewRecordService.updateFileViewRecord(fileViewRecord2));
        }else{
            return error("未找到该记录");
        }
    }
    /**
     * 修改文件浏览记录
     */
    @PostMapping("/sign")
    public AjaxResult sign(@RequestBody FileViewRecord fileViewRecord) {
        FileViewRecord fileViewRecord2 = fileViewRecordService.selectFileViewRecordById(fileViewRecord.getId());
        if (fileViewRecord2 != null){
            fileViewRecord2.setViewStatus("acknowledged");
            fileViewRecord2.setUpdateTime(new Date());
            fileViewRecordService.updateFileViewRecord(fileViewRecord2);
            return success("签阅成功");
        }else{
            return error("未找到该记录");
        }
    }
//
//    /**
//     * 导出文件浏览记录列表
//     */
//    @PreAuthorize("@ss.hasPermi('business:record:export')")
//    @Log(title = "文件浏览记录", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, FileViewRecord fileViewRecord) {
//        List<FileViewRecord> list = fileViewRecordService.selectFileViewRecordList(fileViewRecord);
//        ExcelUtil<FileViewRecord> util = new ExcelUtil<FileViewRecord>(FileViewRecord.class);
//        util.exportExcel(response, list, "文件浏览记录数据");
//    }
//
//    /**
//     * 获取文件浏览记录详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('business:record:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") String id) {
//        return success(fileViewRecordService.selectFileViewRecordById(id));
//    }
//
//    /**
//     * 新增文件浏览记录
//     */
//    @PreAuthorize("@ss.hasPermi('business:record:add')")
//    @Log(title = "文件浏览记录", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody FileViewRecord fileViewRecord) {
//        return toAjax(fileViewRecordService.insertFileViewRecord(fileViewRecord));
//    }
//
//    /**
//     * 修改文件浏览记录
//     */
//    @PreAuthorize("@ss.hasPermi('business:record:edit')")
//    @Log(title = "文件浏览记录", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody FileViewRecord fileViewRecord) {
//        return toAjax(fileViewRecordService.updateFileViewRecord(fileViewRecord));
//    }
//
//    /**
//     * 删除文件浏览记录
//     */
//    @PreAuthorize("@ss.hasPermi('business:record:remove')")
//    @Log(title = "文件浏览记录", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable String[] ids) {
//        return toAjax(fileViewRecordService.deleteFileViewRecordByIds(ids));
//    }
}
